package com.base.springboot.starter.swagger2.autoconfigure;

import com.base.springboot.starter.swagger2.properties.Swagger2Properties;
import com.base.springboot.starter.swagger2.service.SwaggerDisplayConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

import java.util.ArrayList;
import java.util.List;

/**
 * @author HX
 * @date 2020/8/20 下午3:48
 */
@Slf4j
@Configuration
@EnableConfigurationProperties({Swagger2Properties.class})
@ConditionalOnClass({SwaggerDisplayConfig.class})
@Profile({"test", "dev"})
public class Swagger2Configuration {

    @Autowired
    private Swagger2Properties swagger2Properties;

    @Bean
    public Docket createRestApi() {
        //添加header参数
        List<Parameter> pars = new ArrayList<>();
        ParameterBuilder tokenPar = new ParameterBuilder();
        //header中的ticket参数非必填，传空也可以
        tokenPar.name("X-Token").description("user token").modelRef(new ModelRef("string")).parameterType("header").required(false).build();
        pars.add(tokenPar.build());

        //header中的ticket参数非必填，传空也可以
        ParameterBuilder permissionKeyPar = new ParameterBuilder();
        permissionKeyPar.name("permissionKey").description("permissionKey").modelRef(new ModelRef("string")).parameterType("header").required(false).build();
        pars.add(permissionKeyPar.build());

        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.base"))
                .paths(PathSelectors.any())
                .build()
                .apiInfo(this.apiInfo())
                .globalOperationParameters(pars);
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title(swagger2Properties.getTitle())
                .version("1.1.0.RELEASE")
                .contact(new Contact(swagger2Properties.getContractName(), "",
                        swagger2Properties.getContractEmail()))
                .build();

    }
}
